from django.shortcuts import render
from django.http import HttpResponse, HttpResponseBadRequest
import datetime, json
import dynamicloselist.models as models
import logging
# Create your views here.

logger = logging.getLogger(__name__)
collectLogger = logging.getLogger('collect')
DEFAULT_LOST_RATE = [(1, 100), (2, 50), (3, 33), (4, 13), (5, 9), (6, 6), (7, 4), (8, 3)]
DES_RATE = []

# Create your views here.

# 添加 学习记录  在更新 plan时调用
# 学习记录
def add_learn_log(data):
    userId = data.get('userId')
    cardId = data.get('cardId')
    learnCount = data.get('learnCount')
    logInfo = data.get('logInfo')
    # 获取现在日期
    nowTime = datetime.datetime.now().date()

    # 获取 用户 学习了 当前次数的 学习记录 countLog
    countLog = models.LearnLog.objects.filter(
        userId=userId,
        learnCount=learnCount,
    )

    # 获取 用户 countLog 中 当前 card 的 cardLog
    cardLog = countLog.filter(cardId=cardId,)
    # 如果没有 这张卡片 的学习记录 ，则
    if cardLog.count() == 0:
        # 1.添加 学习记录
        newLearnLog = models.LearnLog(
            userId=userId,
            cardId=cardId,
            learnCount=learnCount,
            logInfo=logInfo,
            logTime=nowTime,
        )
        newLearnLog.save()
        # 2.更新 lose rate
        # 2.1 获取 当前用户 当前次数 的 lose_rate
        loseRate = models.LoseRate.objects.get(
            userId=userId,
            learnCount=learnCount
        )
        lastLoseRate = loseRate.loseRate # 原 衰减度
        lastUpdateTime = loseRate.lastUpdateTime # 原 更新时间
        # 2.2 如果 距离上次更新 超过3天，则 更新
        # 1. 获取 最近 7 天 学习 记录
        # 2. 判断数据量是否足够
        # 3. 选择 rate 如何变化,更新 updatetime
        # 4. 保存更新
        if (nowTime - lastUpdateTime).days >= 3:
            # 获取 最近 7 天 的学习记录
            last7days_learnlog = models.LearnLog.objects.filter(
                logTime__gt=nowTime+datetime.timedelta(days=7),
            )
            all_count = last7days_learnlog.count
            if all_count > 100:
                not_forget_count = all_count-last7days_learnlog.filter(
                    logInfo='know'
                ).count()
                forget_count = all_count-last7days_learnlog.filter(
                    logInfo='unknow'
                ).count()
                if forget_count/all_count > 0.8:
                    new_lose_rate = 200*lastLoseRate//(lastLoseRate+200)
                    loseRate.loseRate = new_lose_rate
                    loseRate.lastUpdateTime = nowTime
                    collectLogger.info('loseRate change:userid{}learnCount{}:{}->{}'.format(
                        userId, learnCount, loseRate, new_lose_rate
                    ))
                    loseRate.save()
                elif not_forget_count/all_count > 0.8:
                    new_lose_rate = 200 * lastLoseRate // (lastLoseRate + 200)
                    loseRate.loseRate = new_lose_rate
                    loseRate.lastUpdateTime = nowTime
                    collectLogger.info('loseRate change:userid{}learnCount{}:{}->{}'.format(
                        userId, learnCount, loseRate, new_lose_rate
                    ))
                    loseRate.save()

        result = 1
    # 如果 有记录
    else:
        result = 1
    logger.debug('记录结果：{}'.format(result))
    return result


# 获取用户 lose rate   需要修改 point 时调用
# data{'userId':userId}
# [lose_rate]/[]
def get_lose_rate(data):
    user_id = data.get('userId')
    try:
        lose_rate_list = models.LoseRate.objects.filter(
            userId=user_id,
        ).order_by('learnCount')
        result = []
        for lose_rate in lose_rate_list:
            result.append(lose_rate.loseRate)
        logger.debug('获取到lose_rate:{}'.format(result))
    except Exception as e:
        logger.error(e)
        result = []
        logger.debug('获取到lose_rate:{}'.format(result))
    return result


# 为用户 创建 lose rate 添加用户时调用
# data{'userId':userid}
# 0/1
def create_lose_rate(data):
    user_id = data.get('userId')
    try:
        logger.debug('{}创建lostrate'.format(user_id))
        lost_rate = []
        now_time = datetime.datetime.now().date()
        for count, rate in DEFAULT_LOST_RATE:
            lost_rate.append(
                models.LoseRate(
                    userId=user_id,
                    learnCount=count,
                    loseRate=rate,
                    lastUpdateTime=now_time,
                )
            )
        logger.debug('loseRate:{}'.format(lost_rate))
        models.LoseRate.objects.bulk_create(lost_rate)
        result = 1
    except Exception as e:
        logger.debug('{}'.format(e))
        logger.error(e)
        result = 0
    logger.debug('{}'.format(result))
    return result


